﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Document_Management
{
    public partial class frmjieyong : Form
    {
        static string connectionString = ConfigurationManager.ConnectionStrings["庫存管理"].ConnectionString;
        SqlConnection con = new SqlConnection(connectionString);
        string jieyong, tbj0, tbj1, tbj2, tbj3, tbj4, tbj5, tbj6, tbj7, tbj8, tbj9, tbjn1, tbjn2, tbjn3, tbjn4, tbjn5;
        bool b量具Search, b量具Insert, b量具Edit, b量具Del;
        public frmjieyong(string jieyong, string tbj0, string tbj1, string tbj2, string tbj3, string tbj4, string tbj5, string tbj6, string tbj7, string tbj8, string tbj9, string tbjn1, string tbjn2, string tbjn3, string tbjn4, string tbjn5,bool b量具Search,bool b量具Insert,bool b量具Edit,bool b量具Del)
        {
            InitializeComponent();
            this.tbj0 = tbj0;
            this.tbj1 = tbj1;
            this.tbj2 = tbj2;
            this.tbj3 = tbj3;
            this.tbj4 = tbj4;
            this.tbj5 = tbj5;
            this.tbj6 = tbj6;
            this.jieyong = jieyong;
            this.tbj7 = tbj7;
            this.tbj8 = tbj8;
            this.tbj9 = tbj9;
            this.tbjn1 = tbjn1;
            this.tbjn2 = tbjn2;
            this.tbjn3 = tbjn3;
            this.tbjn4 = tbjn4;
            this.tbjn5 = tbjn5;
            this.b量具Search = b量具Search;
            this.b量具Insert = b量具Insert;
            this.b量具Edit = b量具Edit;
            this.b量具Del = b量具Del;
        }

        private void frmjieyong_Load(object sender, EventArgs e)
        {
            txt量具狀態.Enabled = false;
            txt量具狀態.Text = "借用";

            // goi du lieu lay san pham dung
            if (jieyong == "1")
            {
                btn_Save.Text = "存檔";
                label1.Text = "量具借用";
                txt_量具編號.Text = tbj1;//tb1 0
                txt_Name量具.Text = tbj3; //tb4 3
                txt_規格型式.Text = tbj4;//cb1 1
                txt_存放地點.Text = tbj5; //tb3 2
                txt_測量範圍.Text = tbj6; //cb2  4
            }
            // goi du lieu Tra san pham ve kho
            if (jieyong == "2")
            {
                label1.Text = "量具歸還";
                btn_Save.Text = "歸還";
                hiden();
                label10.Visible = false;
                txt_借用部門.Visible = false;
                lbName借用部門.Visible = false;
                btnSearch借用部門.Visible = false;
                txt_量具編號.Text = tbj1;//tb1 0
                txt量具狀態.Text = tbj2;
                txt_Name量具.Text = tbj3; //tb4 3
                txt_規格型式.Text = tbj4;//cb1 1
                txt_存放地點.Text = tbj5; //tb3 2
                txt_測量範圍.Text = tbj6; //cb2  4
                txt數量.Text = "";
                txt_Date借用.Text = tbj8;
                txt_Date歸還.Text = tbj9;
                txt預還日期.Text = tbjn1;
                txt_借用人.Text = tbjn2;
                txt_借用原因.Text = tbjn3;
                txt_受理人.Text = tbjn4;
                txt_note.Text = tbjn5;
            }
        }

        public void hiden() {
            btn借用紀錄.Enabled = false;
            txt_量具編號.Enabled = false;
            txt量具狀態.Enabled = false;
            txt_Name量具.Enabled = false;
            txt_規格型式.Enabled = false;
            txt_存放地點.Enabled = false;
            txt_測量範圍.Enabled = false;
            txt數量.Enabled = true;
            txt_Date借用.Enabled = false;
            txt_Date歸還.Enabled = true;
            txt預還日期.Enabled = true;
            txt_借用人.Enabled = false;
            txt_借用原因.Enabled = true;
            txt_受理人.Enabled = true;
            txt_note.Enabled = true;
        }

        private void btn_Cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btn借用紀錄_Click(object sender, EventArgs e)
        {
            frmjieyongjilu frm = new frmjieyongjilu(b量具Search, b量具Insert, b量具Edit, b量具Del);
            frm.ShowDialog();
        }

        private void txt_量具編號_TextChanged(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(connectionString);
            try
            {
                con.Open();
                String temp = "";
                string strcmd = String.Format("select * from 量具訊息 where 量具編號=N'{0}'", txt_量具編號.Text);
                SqlCommand cmd = new SqlCommand(strcmd, con);
                var x = cmd.ExecuteReader();
                //int icount=0;
                while (x.Read()) temp = x[1].ToString();
                if (temp == "") lbName量具編號.Text = "";
                else lbName量具編號.Text = temp;
                con.Close();
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
        }

        private void txt_存放地點_TextChanged(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(connectionString);
            try
            {
                con.Open();
                String temp = "";
                string strcmd = String.Format("select * from 存放地點訊息 where 存放地點代號=N'{0}'", txt_存放地點.Text);
                SqlCommand cmd = new SqlCommand(strcmd, con);
                var x = cmd.ExecuteReader();
                //int icount=0;
                while (x.Read()) temp = x[1].ToString();
                if (temp == "") lbName存放地點.Text = "";
                else lbName存放地點.Text = temp;
                con.Close();
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
        }

        private void txt_借用部門_TextChanged(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(connectionString);
            try
            {
                con.Open();
                String temp = "";
                string strcmd = String.Format("select * from 借用部門 where 借用部門代號=N'{0}'", txt_借用部門.Text);
                SqlCommand cmd = new SqlCommand(strcmd, con);
                var x = cmd.ExecuteReader();
                //int icount=0;
                while (x.Read()) temp = x[1].ToString();
                if (temp == "") lbName借用部門.Text = "";
                else lbName借用部門.Text = temp;
                con.Close();
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
        }

        private void btnSearch借用部門_Click(object sender, EventArgs e)
        {
            frmSearchjieyongbumen frm = new frmSearchjieyongbumen(txt_借用部門);
            frm.ShowDialog();
        }

        private void txt_受理人_TextChanged(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(connectionString);
            try
            {
                con.Open();
                String temp = "";
                string strcmd = String.Format("select * from 借用_受理人 where 受理人代號=N'{0}'", txt_受理人.Text);
                SqlCommand cmd = new SqlCommand(strcmd, con);
                var x = cmd.ExecuteReader();
                //int icount=0;
                while (x.Read()) temp = x[1].ToString();
                if (temp == "") lbName受理人.Text = "";
                else lbName受理人.Text = temp;
                con.Close();
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
        }

        private void btnSearch受理人_Click(object sender, EventArgs e)
        {
            frmSearchJieYongShouliren frm = new frmSearchJieYongShouliren(txt_受理人);
            frm.ShowDialog();
        }

        private void txt_借用人_VisibleChanged(object sender, EventArgs e)
        {
            
        }

        private void btnSearch借用人_Click(object sender, EventArgs e)
        {
            frmSearchJieYongRren frm = new frmSearchJieYongRren(txt_借用人);
            frm.ShowDialog();
        }

        private void btn_Save_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(connectionString);
            if (!b量具Insert)
            {
                MessageBox.Show("很抱歉，您沒有權限！", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else
            {
                try
                {
                    // lay san pham su dung
                    if (jieyong == "1")
                    {
                        if (txt_量具編號.Text == "")
                        {
                            MessageBox.Show("請您輸入量具編號", "錯誤", MessageBoxButtons.OK);
                            txt_量具編號.Focus();
                            return;
                        }
                        if (txt量具狀態.Text == "")
                        {
                            MessageBox.Show("請您輸入量具狀態", "錯誤", MessageBoxButtons.OK);
                            txt量具狀態.Focus();
                            return;
                        }
                        if (txt數量.Text == "")
                        {
                            MessageBox.Show("請您輸入領用數量", "錯誤", MessageBoxButtons.OK);
                            txt數量.Focus();
                            return;
                        }
                        if (txt_Date借用.Text == "")
                        {
                            MessageBox.Show("請您輸入借用日期", "錯誤", MessageBoxButtons.OK);
                            txt_Date借用.Focus();
                            return;
                        }
                        if (txt_Date歸還.Text == "")
                        {
                            MessageBox.Show("請您輸入歸還日期", "錯誤", MessageBoxButtons.OK);
                            txt_Date歸還.Focus();
                            return;
                        }

                        if (txt_借用人.Text == "")
                        {
                            MessageBox.Show("請您輸入借用人代號", "錯誤", MessageBoxButtons.OK);
                            txt_借用人.Focus();
                            return;
                        }

                        if (txt_受理人.Text == "")
                        {
                            MessageBox.Show("請您輸入受理人", "錯誤", MessageBoxButtons.OK);
                            txt_受理人.Focus();
                            return;
                        }
                        // kiem tra thoi gian
                        DateTime a = DateTime.Parse(txt_Date借用.Text);
                        DateTime b = DateTime.Parse(txt_Date歸還.Text);
                        if (a > b)
                        {
                            MessageBox.Show("請您輸入歸還日期 >= 借用日期", "錯誤", MessageBoxButtons.OK);
                            txt_Date歸還.Focus();
                            return;
                        }
                        // kiem tra nhap shuliang nho hon so luong trong kho
                        SqlCommand sqlcmd = new SqlCommand();
                        sqlcmd.Connection = con;
                        con.Open();
                        sqlcmd.CommandText = "select 数量 from 量具訊息 where 量具編號=" + "N'" + tbj1 + "'";
                        sqlcmd.CommandType = CommandType.Text;
                        var icount = sqlcmd.ExecuteScalar();
                        int inumdel;
                        bool k = int.TryParse(txt數量.Text, out inumdel);
                        int istocknumber = int.Parse(icount.ToString());
                        int check = int.Parse(txt數量.Text);
                        if (!k || inumdel > int.Parse(icount.ToString()))
                        {
                            MessageBox.Show("請您輸入借用數量量具要刪除(int,<" + istocknumber + ")", "錯誤", MessageBoxButtons.OK);
                            txt數量.Focus();
                            //return;
                        }
                        else if (istocknumber == 0 || check <=0)
                        {
                            MessageBox.Show("不能借用", "錯誤", MessageBoxButtons.OK);
                        }
                        else
                        {
                            // check bo phan     
                            String sqlck = "SELECT COUNT(*) FROM 借用人,借用部門 WHERE 借用人代號='" + txt_借用人.Text.ToString()
                                        + "' AND 借用人.借用部門代號=借用部門.借用部門代號 AND 借用部門.借用部門代號='" + txt_借用部門.Text.ToString() + "'";
                            sqlcmd = new SqlCommand(sqlck, con);
                            if ((int)sqlcmd.ExecuteScalar() == 0)
                            {
                                MessageBox.Show("錯誤:借用人'" + lbName借用人.Text.ToString() +"'没有在借用部門'" + lbName借用部門.Text.ToString()+"''", "錯誤", MessageBoxButtons.OK);
                                txt_借用人.Focus();
                                //return;
                            }
                            else
                            {
                                // tien hanh inset du lieu vao bang lingyong
                                DialogResult answer = MessageBox.Show("您確定要出入" + int.Parse(txt數量.Text) + "量具嗎？", "警報", MessageBoxButtons.YesNo);
                                if (answer == DialogResult.Yes)
                                {
                                    //automation inset
                                    string sp_insert = "sp_借用_新增";
                                    SqlCommand cmd = new SqlCommand(sp_insert, con);
                                    cmd.CommandType = CommandType.StoredProcedure;
                                    cmd.Parameters.AddWithValue("@量具編號", txt_量具編號.Text);
                                    cmd.Parameters.AddWithValue("@量具狀態", txt量具狀態.Text);
                                    cmd.Parameters.AddWithValue("@量具名稱", txt_Name量具.Text);
                                    cmd.Parameters.AddWithValue("@規格型號", txt_規格型式.Text);
                                    cmd.Parameters.AddWithValue("@存放地點", txt_存放地點.Text.ToString());
                                    cmd.Parameters.AddWithValue("@測量範圍", txt_測量範圍.Text.ToString());
                                    cmd.Parameters.AddWithValue("@數量", Int32.Parse(txt數量.Text));
                                    cmd.Parameters.AddWithValue("@借用日期", DateTime.Parse(txt_Date借用.Text));
                                    cmd.Parameters.AddWithValue("@歸還日期", DateTime.Parse(txt_Date歸還.Text));
                                    cmd.Parameters.AddWithValue("@預還日期", DateTime.Parse(txt預還日期.Text));
                                    cmd.Parameters.AddWithValue("@借用人代號", txt_借用人.Text);
                                    cmd.Parameters.AddWithValue("@借用原因", txt_借用原因.Text);
                                    cmd.Parameters.AddWithValue("@受理人代號", txt_受理人.Text.ToString());
                                    cmd.Parameters.AddWithValue("@備註", txt_note.Text);
                                    cmd.ExecuteNonQuery();

                                    //ling yong liang ju
                                    string delete = tbj1;
                                    //string delete1 = tbl6;
                                    string sp_increment = "sp_量具訊息_更新_-n";// tru so luong san pham trong kho khi linh yong
                                    SqlCommand sqlincrement = new SqlCommand();
                                    sqlincrement.Connection = con;
                                    sqlincrement.CommandType = CommandType.StoredProcedure;
                                    sqlincrement.CommandText = sp_increment;
                                    sqlincrement.Parameters.AddWithValue("@量具編號", delete);
                                    //sqlincrement.Parameters.AddWithValue("@量具狀態", delete1);
                                    sqlincrement.Parameters.AddWithValue("@n", int.Parse(txt數量.Text));
                                    sqlincrement.ExecuteNonQuery();

                                    //string dele = "Select 數量 from 領用";

                                    MessageBox.Show("領用成功");
                                    con.Close();
                                    this.Close();
                                    frmjieyongjilu frm = new frmjieyongjilu(b量具Search, b量具Insert, b量具Edit, b量具Del);
                                    frm.ShowDialog();
                                    this.Close();
                                }
                                else return;
                            }
                        }
                    }
                    //tra san pham ling yong
                    if (jieyong == "2")
                    {
                        //==============================================================================
                        if (txt數量.Text == "")
                        {
                            MessageBox.Show("請您輸入修理數量", "錯誤", MessageBoxButtons.OK);
                            txt數量.Focus();
                            return;
                        }
                        int check = int.Parse(txt數量.Text);
                        if (check <= 0)
                        {
                            MessageBox.Show("不能歸還數量<=0", "錯誤", MessageBoxButtons.OK);
                            txt數量.Focus();
                            return;
                        }
                        else
                        {
                            // kiem tra so luong tra nho hon so luong ling yong
                            SqlCommand sqlcmd = new SqlCommand();
                            sqlcmd.Connection = con;
                            con.Open();
                            sqlcmd.CommandText = "select 數量 from 借用 where 項次=" + "N'" + tbj0 + "'";
                            sqlcmd.CommandType = CommandType.Text;
                            var icount = sqlcmd.ExecuteScalar();
                            int inumdel;
                            bool k = int.TryParse(txt數量.Text, out inumdel);
                            int istocknumber = int.Parse(icount.ToString());
                            if (!k || inumdel > int.Parse(icount.ToString()))
                            {
                                MessageBox.Show("請您輸入借用數量量具要刪除(int,<" + istocknumber + ")", "錯誤", MessageBoxButtons.OK);
                                txt數量.Focus();
                                return;
                            }
                            if (inumdel == istocknumber)//delete from database
                            {
                                DialogResult answer1 = MessageBox.Show("您確定要出入" + inumdel + "借用量具碼", "警報", MessageBoxButtons.YesNo);
                                if (answer1 == DialogResult.Yes)
                                {
                                //DialogResult answer2 = MessageBox.Show("Bạn có muốn xóa A trong 修理紀錄 khi trả về 5 量具 va số lượng còn lại la bằng 0, hay ko ？", "警報", MessageBoxButtons.YesNo);
                                    DialogResult answer2 = MessageBox.Show("當歸還" + inumdel + "量具及存借用紀錄的量具剩余數量是0的，要不要刪除這個量具？", "警報", MessageBoxButtons.YesNo);
                                if (answer2 == DialogResult.Yes)
                                {
                                    //con.Open();
                                    string sp_delete = "sp_借用_刪除";
                                    SqlCommand sqldelete = new SqlCommand();
                                    sqldelete.Connection = con;
                                    sqldelete.CommandType = CommandType.StoredProcedure;
                                    sqldelete.CommandText = sp_delete;
                                    sqldelete.Parameters.AddWithValue("@項次", tbj0);
                                    //MessageBox.Show("刪除成功");
                                    sqldelete.ExecuteNonQuery();
                                }
                                if (answer2 == DialogResult.No)
                                {
                                    string delete = tbj0;
                                    //string delete1 = tbl6;
                                    string sp_increment = "sp_借用_更新_-n"; // tru ling yong
                                    SqlCommand sqlincrement = new SqlCommand();
                                    sqlincrement.Connection = con;
                                    sqlincrement.CommandType = CommandType.StoredProcedure;
                                    sqlincrement.CommandText = sp_increment;
                                    sqlincrement.Parameters.AddWithValue("@項次", delete);
                                    //sqlincrement.Parameters.AddWithValue("@量具狀態", delete1);
                                    sqlincrement.Parameters.AddWithValue("@n", int.Parse(txt數量.Text));
                                    sqlincrement.ExecuteNonQuery();
                                }
                                // Sửa ngày dự định trở về kho thành ngày trở về thực tế
                                //string sp_update修理 = "sp_借用_更新";
                                //SqlCommand cmd = new SqlCommand(sp_update修理, con);
                                //cmd.CommandType = CommandType.StoredProcedure;
                                //cmd.Parameters.AddWithValue("@量具編號", txt_量具編號.Text);
                                //cmd.Parameters.AddWithValue("@歸還日期", DateTime.Parse(txt_Date歸還.Text));
                                //cmd.Parameters.AddWithValue("@預還日期", DateTime.Parse(txt預還日期.Text));
                                //cmd.Parameters.AddWithValue("@借用人代號", txt_借用人.Text);
                                //cmd.Parameters.AddWithValue("@借用原因", txt_借用原因.Text);
                                //cmd.Parameters.AddWithValue("@受理人代號", txt_受理人.Text.ToString());
                                //cmd.Parameters.AddWithValue("@備註", txt_note.Text);
                                //cmd.ExecuteNonQuery();
                                //Tra ve
                                string sp_update = "sp_量具訊息_更新_+n"; // cong vao kho
                                SqlCommand cmd1 = new SqlCommand(sp_update, con);
                                cmd1.CommandType = CommandType.StoredProcedure;
                                cmd1.Parameters.AddWithValue("@量具編號", txt_量具編號.Text);
                                //cmd1.Parameters.AddWithValue("@量具狀態", txt量具狀態.Text.ToString());
                                cmd1.Parameters.AddWithValue("@n", txt數量.Text);
                                cmd1.ExecuteNonQuery();
                                MessageBox.Show("歸還成功");
                                this.Close();
                                con.Close();
                                }
                                else
                                {
                                    return;
                                }
                            }
                            else
                            {
                                //====================================================================================
                                DialogResult answer = MessageBox.Show("您確定要出入" + int.Parse(txt數量.Text) + "量具嗎？", "警報", MessageBoxButtons.YesNo);
                                if (answer == DialogResult.Yes)
                                {
                                    //con.Open();
                                    //tra ve
                                    string delete = tbj0;
                                    //string delete1 = tbl6;
                                    string sp_increment = "sp_借用_更新_-n";// tru ling yong
                                    SqlCommand sqlincrement = new SqlCommand();
                                    sqlincrement.Connection = con;
                                    sqlincrement.CommandType = CommandType.StoredProcedure;
                                    sqlincrement.CommandText = sp_increment;
                                    sqlincrement.Parameters.AddWithValue("@項次", delete);
                                    //sqlincrement.Parameters.AddWithValue("@量具狀態", delete1);
                                    sqlincrement.Parameters.AddWithValue("@n", int.Parse(txt數量.Text));
                                    sqlincrement.ExecuteNonQuery();

                                    //Tra ve
                                    string sp_update = "sp_量具訊息_更新_+n"; // cong vao kho
                                    SqlCommand cmd1 = new SqlCommand(sp_update, con);
                                    cmd1.CommandType = CommandType.StoredProcedure;
                                    cmd1.Parameters.AddWithValue("@量具編號", txt_量具編號.Text);
                                    //cmd1.Parameters.AddWithValue("@量具狀態", txt量具狀態.Text.ToString());
                                    cmd1.Parameters.AddWithValue("@n", txt數量.Text);
                                    cmd1.ExecuteNonQuery();
                                    MessageBox.Show("歸還成功");
                                    con.Close();
                                    this.Close();
                                }
                                else return;
                            }
                        }
                    }
                }
                catch (Exception ex) { con.Close(); MessageBox.Show(ex.Message); }
                finally { con.Close(); }
            }
        }

        private void txt數量_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) || e.KeyChar == '.')
            {
                e.Handled = true;
                MessageBox.Show("請您輸入號碼", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btn_Save_TextChanged(object sender, EventArgs e)
        {
            
        }

        private void txt_借用人_TextChanged(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(connectionString);
            try
            {
                con.Open();
                String temp = "";
                string strcmd = String.Format("select * from 借用人 where 借用人代號=N'{0}'", txt_借用人.Text);
                SqlCommand cmd = new SqlCommand(strcmd, con);
                var x = cmd.ExecuteReader();
                //int icount=0;
                while (x.Read()) temp = x[2].ToString();
                if (temp == "") lbName借用人.Text = "";
                else lbName借用人.Text = temp;
                con.Close();
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
        }
    }
}
